scriptSupport.addInit(function() {
	var doc = Doc();

	new EventListener(doc.doc, "keydown", doc.handleKeyEvent, doc);

	new EditSelectionSupport(doc, EntityView.getFirstChildEntityView(doc.contentPanel.element));

	// if (!E.Config.get("EditMode").suppressToggle)
	// toggleEditMode();
});

function toggleEditMode() {
	var doc = Doc(document);
	doc.inEditMode = !doc.inEditMode;
	StatusDisplay.getInstance().show(
		"switching into " + ((doc.inEditMode)?"edit":"normal") + " mode...", null, true);
	if (!doc.editorPanel) {
		// doc.addCss(BasePath.get() + "/livcos.org/web/css/edit.css");
		doc.editorPanel = new EditorPanel(doc);
		doc.templatePanel = new TemplatePanel(doc);
		doc.selectionPanel = new SelectionPanel(doc);
	}
	doc.applyEditFeatures();
	doc.inlineEdit.active = doc.inEditMode;
	if (doc.editModeCookie) {
		if (doc.inEditMode)
			doc.editModeCookie.setValue("1", 1);
		else
			doc.editModeCookie.setValue("0", -1);
	}
	doc.selectionSupport.activate(doc.inEditMode);
	if (!doc.inEditMode)
		doc.selectionPanel.display(doc.inEditMode);
	if (doc.editModeImage) {
		doc.editModeImage.src = BasePath.get() + EDIT_IMAGE_BASE
			+ ((doc.inEditMode)?"/editMode.gif":"/readMode.png");
		doc.zoomEditToggle();
	}
	ContextPanel.clear();
	if (typeof(onToggleEditMode) == "function")
		onToggleEditMode();
}

E.Doc.prototype.applyEditFeatures = function() {
	var evs = EntityView.getEntityViews();
	for (var i = 0; i < evs.length; i++)
		evs[i].applyEditMode(this.inEditMode);
	if (!this.inEditMode)
		return;
	var nodes = this.contentPanel.getElementsByClassName("inlineEdit");
	for (var i = 0; i < nodes.length; ++i) {
		var n = nodes[i];
		var e = Dom(n);
		if (!e.inlineEdit) {
			e.setInlineEdit(function(val) {
					var e = this.dom.getEntityView();
					var path = this.dom.element.getAttribute("title");
					if (!path)
						path = ".";
					var a = new UpdateValueAction(e, val, path);
					a.perform();
				}, "-- text --");
		}
	}
}

E.Doc.prototype.lock = function() {
	this.locked = true;
	this.selectionSupport.process();
	this.contentPanel.element.style.cursor = "wait";
}

E.Doc.prototype.unlock = function() {
	this.contentPanel.element.style.cursor = "";
	this.selectionSupport.activate(false);
	this.locked = false;
}

E.Doc.prototype.handleKeyEvent = function(evn) {
	// alert(evn.keyCode);
	if (evn.keyCode == 27) { // ESC
		this.editorPanel && this.editorPanel.close();
		this.templatePanel && this.templatePanel.close();
		return;
	}
	var slSp = this.selectionSupport;
	if (this.inEditMode && slSp.current && !this.editorPanel.isOpen && !Dom(evn.target).isTextEdit()) {
		var a = null;
		if (evn.ctrlKey) {
			if (evn.keyCode == 67) // Ctrl-C
				a = new CopyAction(slSp.current.entityView);
			else if (evn.keyCode == 88) // Ctrl-X
				a = new CutAction(slSp.current.entityView);
			else if ((evn.keyCode == 86) && evn.shiftKey) // Ctrl-Shift-V
				a = new PasteIntoAction(slSp.current.entityView);
			else if (evn.keyCode == 86) // Ctrl-V
				a = new PasteAction(slSp.current.entityView);
			else if (evn.keyCode == 90) // Ctrl-Z
				a = new UndoAction(slSp.current.entityView);
			else if ((evn.keyCode == 13) && evn.shiftKey) // Ctrl-Shift-Enter
				a = new CreateAction(slSp.current.entityView);
			else
				return;
		}
		else {
			if (evn.keyCode == 46) // Delete
				a = new DeleteAction(slSp.current.entityView);
			else if ((evn.keyCode == 45) && !E.Config.get("EditMode").suppressTemplatePanel) // Insert
				this.templatePanel.open();
			else if (evn.keyCode == 69) // E
				this.editorPanel.open();
			else if (evn.keyCode == 67) // C
				a = new CloneAction(slSp.current.entityView);
			else if (evn.keyCode == 83) // S
				this.selectionPanel.display(!this.selectionPanel.isVisible());
			else
				return;
		}
		if (a)
			a.perform();
	}
	else if (evn.ctrlKey && evn.shiftKey) {
		if ((evn.keyCode == 77) || (evn.keyCode == 93)) { // Ctrl-Shift-M or
			// -Windows Properties Key
			// (context menu key)
			if (this.showSystemContextMenu)
				this.showSystemContextMenu(-1, -1, false);
		}
		else
			return;
	}
	else
		return;
	return EventListener.cancelEvent(evn);
}

EditSelectionSupport = function(doc, initialEntityView) {
	EditSelectionSupport._super.call(this, doc, initialEntityView);
}
Object.extend("EditSelectionSupport", "E.SelectionSupport");

EditSelectionSupport.prototype.isSelectable = function(dom) {
	var doc = Doc(dom);
	return !((!doc.inEditMode) || dom.hasAncestor(doc.doc.statusDisplay.element)
		|| dom.hasAncestor(doc.editorPanel.element) || dom.hasAncestorWithClass("contextPanel") || dom
		.hasAncestorWithClass("editModeToggle"));
}

EditSelectionSupport.prototype.onContextMenu = function(evn) {
	var sel = this.current;
	var ev = sel.entityView;
	var e = ev.dom.element;
	if ("keydown" == evn.type)
		evn = {
			clientX : 0,
			clientY : 0,
			target : e,
			type : "keydown"
		};
	var s = Dom(e).getScrollVector();
	var x = evn.clientX + s[0];
	var y = evn.clientY + s[1];
	var p = Dom(e).getVector();
	if (y < p[1])
		y = p[1] + 2;
	else if (y > (p[1] + e.offsetHeight))
		y = p[1] + e.offsetHeight - 2;
	if (x < p[0])
		x = p[0] + 10;
	else if (x > (p[0] + e.offsetWidth))
		x = p[0] + e.offsetWidth - 10;
	var cp = new ContextPanel();
	cp.show(evn.target, x, y, evn);
	// sel.addPanelToHide(cp);
	ev.entity.load(function() {
			var cm = new Menu();
			if (this.menu) {
				var nodes = this.menu.childNodes;
				for (var i = 0; i < nodes.length; ++i) {
					var n = nodes[i];
					var tagName = (n.localName)?n.localName:n.nodeName;
					if ("action" == tagName) {
						var actType = n.getAttribute("type");
						if (typeof(window[actType]) != "function")
							continue;
						var act;
						eval("act = new " + actType + "();");
						act.entity = this;
						act.entityView = ev;
						var editorId = null;
						var disabled = false;
						var attrs = n.attributes;
						for (var j = 0; j < attrs.length; ++j) {
							var a = attrs[j];
							if ("type" == a.name)
								continue;
							if ("editor" == a.name) {
								editorId = a.value;
								continue;
							}
							if ("disabled" == a.name) {
								disabled = a.value != "0";
								continue;
							}
							if ("path" == a.name)
								act.namespaces = n.getElementsByTagName("namespace");
							act[a.name] = a.value;
						}
						if (editorId)
							act = new ShowEditorAction(ev, editorId, act);
						if (disabled)
							act.disabled = true;
						cm.add(new Menu(act));
					}
				}
			}
			cm.add(new Menu(new TransformAction(ev)));
			cm.add(new Menu(new UndoAction(ev)));
			cm.add(new Menu(new OpenDataAction(ev)));
			cp.setContent(cm);
		});
}

EditSelectionSupport.prototype.onCancel = function(evn) {
	if (this.doc.contextPanel) {
		ContextPanel.clear();
	}
	else if (this.doc.editorPanel && this.doc.editorPanel.isOpen) {
		if (!this.doc.editorPanel.hasInputChanged()
			|| confirm("Your changes have not been saved!\n\nDiscard these changes?"))
			this.doc.editorPanel.close();
	}
	else {
		this.current && this.current.activate(false);
	}
}

EditSelectionSupport.prototype.createSelection = function(entityView) {
	return new EditSelection(entityView);
};

EditSelection = function(entityView) {
	EditSelection._super.call(this, entityView);
	this.doc = Doc(this.entityView.dom.element.ownerDocument);
}
Object.extend("EditSelection", "E.Selection");

EditSelection.prototype.activate = function(active, scrollIntoView) {
	if (!active && this.doc.editorPanel && this.doc.editorPanel.isOpen
		&& this.doc.editorPanel.hasInputChanged()
		&& !confirm("Your changes have not been saved!\n\nDiscard these changes?"))
		return false;
	EditSelection._super.prototype.activate.call(this, active, scrollIntoView);
	this.entityView.selectForEdit(active, scrollIntoView);
	if (this.doc.selectionPanel)
		this.doc.selectionPanel.setEntityView(this.entityView);
	if (this.doc.editorPanel) {
		if (active)
			this.doc.editorPanel.setEntityView(this.entityView);
		else
			this.doc.editorPanel.close();
	}
	if (this.doc.templatePanel) {
		if (active)
			this.doc.templatePanel.setEntityView(this.entityView);
		else
			this.doc.templatePanel.close();
	}
	return true;
}

EditSelection.prototype.perform = function() {
	var dom = this.entityView.dom;
	if ((this.doc.editorPanel && this.doc.editorPanel.isOpen) || this.doc.contextPanel)
		return false;
	var url = dom.element.href;
	if (url) {
		top.location.href = url;
		return true;
	}
	return false;
}
